Popular Searches
Popular Course Categories
Popular Courses

Understanding Hierarchical Inheritance

Understanding Hierarchical Inheritance

Encapsulation, Inheritance, and Polymorphism

Understanding Hierarchical Inheritance in Java

Course: Core Java Training

Topic: Understanding Hierarchical Inheritance in Java

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Hierarchical Inheritance

Hierarchical inheritance is a type of inheritance in Java in which two or more child classes inherit properties and methods from the same parent class. The parent class contains common fields and behaviors, while each child class can reuse those members and define its own additional features.

This inheritance structure is useful when multiple classes share common characteristics but also need different implementations or specialized behavior.

For example, a Vehicle class may contain common properties such as brand and speed. Classes such as Car, Bike, and Bus can inherit from Vehicle and add their own features.

2. Definition of Hierarchical Inheritance

Hierarchical inheritance occurs when multiple subclasses extend a single superclass.

In Java, the extends keyword is used when a class inherits from another class.

Key Characteristics

  • One parent class is shared by multiple child classes.
  • Child classes inherit accessible fields and methods from the parent class.
  • Each child class can have its own additional fields and methods.
  • Child classes can override inherited instance methods when appropriate.
  • It encourages code reuse and reduces duplication.
  • Java supports hierarchical inheritance through classes.

3. Structure of Hierarchical Inheritance

The general structure consists of one superclass and multiple subclasses.

          Parent
         /      \
      Child1    Child2
        |
     (own members)

In a common hierarchical inheritance design, all child classes extend the same parent directly. They do not automatically inherit one another's members.

Example Structure

             Animal
            /      \
          Dog       Cat

Here, both Dog and Cat inherit accessible members of Animal. Dog can define bark(), while Cat can define meow().

4. Syntax of Hierarchical Inheritance

class Parent {
    void commonMethod() {
        System.out.println("Common behavior");
    }
}

class ChildOne extends Parent {
    void methodOne() {
        System.out.println("Child One behavior");
    }
}

class ChildTwo extends Parent {
    void methodTwo() {
        System.out.println("Child Two behavior");
    }
}

In this example, both ChildOne and ChildTwo extend Parent. Therefore, objects of both child classes can use the inherited commonMethod(), subject to normal access rules.

5. Example 1: Hierarchical Inheritance Using Animals

This example demonstrates one parent class named Animal and two child classes named Dog and Cat.

class Animal {
    void eat() {
        System.out.println("Animals eat food.");
    }

    void sleep() {
        System.out.println("Animals sleep.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks.");
    }
}

class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.sleep();
        dog.bark();

        Cat cat = new Cat();
        cat.eat();
        cat.sleep();
        cat.meow();
    }
}

Output

Animals eat food.
Animals sleep.
Dog barks.
Animals eat food.
Animals sleep.
Cat meows.

Explanation

  • Animal is the superclass.
  • Dog and Cat are subclasses.
  • Both subclasses inherit the eat() and sleep() methods.
  • The Dog class adds the bark() method.
  • The Cat class adds the meow() method.
  • Each object can use the common inherited methods and its own class-specific methods.

6. Example 2: Hierarchical Inheritance Using Employees

In a business application, different types of employees may share common information but perform different tasks. A common Employee class can hold shared data and behavior.

class Employee {
    String name;
    double salary;

    Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Salary: " + salary);
    }
}

class Developer extends Employee {
    Developer(String name, double salary) {
        super(name, salary);
    }

    void writeCode() {
        System.out.println(name + " writes code.");
    }
}

class Manager extends Employee {
    Manager(String name, double salary) {
        super(name, salary);
    }

    void conductMeeting() {
        System.out.println(name + " conducts a meeting.");
    }
}

public class Main {
    public static void main(String[] args) {
        Developer developer = new Developer("Amit", 60000);
        developer.displayDetails();
        developer.writeCode();

        Manager manager = new Manager("Priya", 80000);
        manager.displayDetails();
        manager.conductMeeting();
    }
}

Output

Name: Amit
Salary: 60000.0
Amit writes code.
Name: Priya
Salary: 80000.0
Priya conducts a meeting.

Explanation

The Employee class stores shared employee details. Developer and Manager inherit those fields and the displayDetails() method. Their constructors call super(name, salary) to initialize the superclass portion of each object. Each subclass also defines its own specific behavior.

7. Example 3: Hierarchical Inheritance Using Vehicles

class Vehicle {
    String brand = "Generic Brand";

    void start() {
        System.out.println("Vehicle starts.");
    }
}

class Car extends Vehicle {
    void openTrunk() {
        System.out.println("Car trunk is open.");
    }
}

class Bike extends Vehicle {
    void kickStart() {
        System.out.println("Bike is kick-started.");
    }
}

class Bus extends Vehicle {
    void carryPassengers() {
        System.out.println("Bus carries passengers.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        System.out.println(car.brand);
        car.start();
        car.openTrunk();

        Bike bike = new Bike();
        bike.start();
        bike.kickStart();

        Bus bus = new Bus();
        bus.start();
        bus.carryPassengers();
    }
}

Output

Generic Brand
Vehicle starts.
Car trunk is open.
Vehicle starts.
Bike is kick-started.
Bus carries passengers.

This example demonstrates how several classes can share a common implementation while maintaining their own specialized behavior.

8. How Hierarchical Inheritance Works

  1. Create a superclass: Define the fields and methods that should be common to related classes.
  2. Create multiple subclasses: Declare each child class using extends followed by the superclass name.
  3. Reuse inherited members: Create child objects and access the superclass's accessible methods and fields.
  4. Add specialized functionality: Define methods or fields specific to each subclass.
  5. Override methods if needed: A subclass may provide its own implementation of an inherited instance method.
  6. Create objects: Use each subclass according to its specific responsibilities.

9. Role of the extends Keyword

The extends keyword establishes a class inheritance relationship. It tells Java that the subclass derives from the specified superclass.

class Parent {
    void show() {
        System.out.println("Parent method");
    }
}

class ChildA extends Parent {
}

class ChildB extends Parent {
}

Both ChildA and ChildB inherit the accessible show() method. The method does not need to be rewritten in either child class.

10. Role of Constructors in Hierarchical Inheritance

Constructors initialize objects. Constructors are not inherited by subclasses, but a subclass constructor can invoke a superclass constructor using super() or super(arguments).

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    int rollNumber;

    Student(String name, int rollNumber) {
        super(name);
        this.rollNumber = rollNumber;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
    }
}

class Teacher extends Person {
    String subject;

    Teacher(String name, String subject) {
        super(name);
        this.subject = subject;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Subject: " + subject);
    }
}

Student and Teacher both extend Person. Each constructor calls the superclass constructor to initialize the inherited name field.

Important: When a constructor does not explicitly invoke another constructor, Java normally inserts a no-argument superclass constructor call where permitted. If the superclass has no accessible no-argument constructor, the subclass must explicitly invoke an appropriate superclass constructor.

11. Method Overriding in Hierarchical Inheritance

Method overriding allows a subclass to provide a specific implementation of an inherited instance method. Different child classes can override the same parent method in different ways.

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound.");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks.");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();

        dog.makeSound();
        cat.makeSound();
    }
}

Output

Dog barks.
Cat meows.

The @Override annotation helps the compiler verify that the method correctly overrides an inherited method. The selected implementation depends on the actual object at runtime.

12. Hierarchical Inheritance and Polymorphism

Polymorphism allows a superclass reference to refer to an object of a subclass. When an overridden instance method is called through that reference, Java selects the implementation belonging to the actual object.

class Shape {
    void draw() {
        System.out.println("Drawing a shape.");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle.");
    }
}

class Rectangle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Rectangle();

        shape1.draw();
        shape2.draw();
    }
}

Output

Drawing a circle.
Drawing a rectangle.

Circle and Rectangle are subclasses of Shape. A common Shape reference can work with objects of either subclass, making the design easier to extend.

13. Advantages of Hierarchical Inheritance

Advantage Description
Code Reusability Common fields and methods are implemented once in the parent class.
Reduced Duplication Shared logic does not need to be repeated in every child class.
Easy Maintenance Common behavior can be updated in one superclass, subject to the effects on subclasses.
Extensibility New subclasses can be introduced to represent additional related types.
Polymorphism Superclass references can work with different subclass objects.
Clear Organization Related classes can be grouped under a meaningful common abstraction.

14. Limitations of Hierarchical Inheritance

  • Tight coupling: Changes to a superclass can affect multiple subclasses.
  • Incorrect parent design: A poorly chosen superclass may force unrelated classes to share inappropriate behavior.
  • Complexity: Large inheritance trees can become difficult to understand and maintain.
  • Limited class inheritance: Java classes can directly extend only one superclass.
  • Access restrictions: Private superclass members cannot be accessed directly by subclasses, although they remain part of the superclass's object state and may be exposed through suitable methods.

Use inheritance when the child classes genuinely represent specialized forms of the parent class. If the relationship is not an appropriate “is-a” relationship, composition may be a better design.

15. Difference Between Hierarchical and Other Inheritance Types

Inheritance Type Structure Example
Single Inheritance One child inherits from one parent. Dog extends Animal
Multilevel Inheritance A class extends another subclass, creating a chain. Animal → Mammal → Dog
Hierarchical Inheritance Multiple children inherit from one parent. Animal → Dog, Cat, Cow
Multiple Inheritance A type inherits from multiple parents. Java classes cannot extend multiple classes directly; interfaces can be implemented together.
Hybrid Inheritance A combination of inheritance patterns. Can be modeled using classes and interfaces within Java's inheritance rules.

16. Access Modifiers in Hierarchical Inheritance

Access modifiers control which inherited members can be accessed from a subclass.

Modifier Subclass Access Important Detail
public Accessible wherever the class and member are visible. Subject to normal class and module accessibility rules.
protected Accessible in subclasses under Java's protected-access rules. Package and cross-package access rules differ.
default (package-private) Accessible to classes in the same package. Not directly accessible to a subclass in a different package solely because of inheritance.
private Not directly accessible by subclass code. Use accessible superclass methods to work with private state when appropriate.

17. Common Mistakes to Avoid

  • Confusing the structure: Hierarchical inheritance means multiple child classes share one parent; it is not a chain of subclasses.
  • Assuming child classes inherit from each other: A Dog class does not inherit Cat's methods just because both extend Animal.
  • Accessing private members directly: Private fields must be accessed through suitable methods provided by the superclass, if available.
  • Forgetting superclass constructor calls: A parameterized superclass constructor may require an explicit super(arguments) call.
  • Overriding with an incompatible signature: Method overriding must follow Java's rules for method signatures and return types.
  • Using inheritance unnecessarily: Do not create inheritance relationships only to reuse a few unrelated methods.
  • Repeating common code: Move genuinely shared functionality into the superclass when it fits the design.

18. Best Practices for Hierarchical Inheritance

  • Use meaningful names for parent and child classes.
  • Place only genuinely common fields and behavior in the superclass.
  • Keep each subclass focused on its specialized responsibilities.
  • Use @Override when overriding methods.
  • Use access modifiers to protect object state and define a clear public API.
  • Prefer composition when a class does not truly represent a specialized form of another class.
  • Use superclass references and polymorphism where they simplify application design.
  • Write tests for shared parent behavior and subclass-specific behavior.

19. Real-World Applications

Parent Class Child Classes Shared Functionality Specialized Functionality
Employee Developer, Manager, Tester Name, employee ID, basic details Coding, team management, software testing
Vehicle Car, Bike, Bus Brand, start, stop Trunk access, kick-start, passenger capacity
Account SavingsAccount, CurrentAccount Account number, balance Account-specific rules and services
Shape Circle, Rectangle, Triangle Common shape operations Shape-specific area or drawing calculations
Notification EmailNotification, SMSNotification Shared notification structure Email or SMS delivery behavior

20. Practice Exercise

Task: Create a Java program demonstrating hierarchical inheritance with a parent class named Appliance and child classes named WashingMachine, Refrigerator, and Microwave.

Requirements

  1. Create a parent class named Appliance.
  2. Add a method named turnOn() that displays a common message.
  3. Create three child classes that extend Appliance.
  4. Add a unique method to each child class.
  5. Create one object of each child class in the main method.
  6. Call the inherited method and the class-specific method on each object.

Sample Output

Appliance is turned on.
Washing machine starts washing.
Appliance is turned on.
Refrigerator starts cooling.
Appliance is turned on.
Microwave starts heating.

21. Mini Project: Employee Role Management

Build a small program that models different employee roles using hierarchical inheritance.

Project Requirements

  • Create an Employee superclass with fields for employee name and ID.
  • Add a method to display common employee details.
  • Create Developer, Designer, and Manager subclasses.
  • Give each subclass a unique method representing its responsibilities.
  • Use constructors to initialize inherited fields.
  • Create objects for all three roles and display their details.

Learning outcome: This project demonstrates shared fields, constructor chaining, inherited methods, and subclass-specific behavior in a practical context.

22. Interview Questions and Answers

Q1. What is hierarchical inheritance in Java?

Answer: Hierarchical inheritance is a relationship in which multiple subclasses extend the same superclass.

Q2. Which keyword is used to implement class inheritance in Java?

Answer: The extends keyword is used when a class inherits from another class.

Q3. Can a parent class have multiple child classes?

Answer: Yes. Multiple subclasses can extend the same parent class.

Q4. Can child classes have their own methods?

Answer: Yes. Each child class can define additional methods and fields that are specific to its purpose.

Q5. Do child classes inherit private fields directly?

Answer: Private fields are not directly accessible in subclass code. A superclass may provide public or protected methods to access or update its state.

Q6. Can different child classes override the same parent method?

Answer: Yes. Each subclass can provide its own implementation of an inherited instance method, provided the overriding rules are satisfied.

Q7. Are constructors inherited in Java?

Answer: No. Constructors are not inherited. A subclass constructor can call a superclass constructor using super() or super(arguments).

Q8. What is the main benefit of hierarchical inheritance?

Answer: It allows multiple related classes to reuse common fields and methods while maintaining their own specialized functionality.

Q9. Can Java support hierarchical inheritance with interfaces?

Answer: Yes. Multiple classes can implement the same interface, creating a similar one-to-many type relationship.

Q10. What is the difference between hierarchical and multilevel inheritance?

Answer: Hierarchical inheritance has multiple child classes extending one parent. Multilevel inheritance creates a chain in which one subclass extends another subclass.

23. Quick Revision Checklist

  • Hierarchical inheritance uses one superclass and multiple subclasses.
  • The extends keyword establishes a class inheritance relationship.
  • Child classes can reuse accessible superclass members.
  • Each child class can add its own fields and methods.
  • Constructors are not inherited; superclass constructors can be called with super().
  • Subclasses can override inherited instance methods.
  • Polymorphism allows a superclass reference to refer to subclass objects.
  • Private members cannot be accessed directly by subclass code.
  • Inheritance should represent a meaningful “is-a” relationship.
  • Practice by creating one parent class and at least two child classes.

24. Conclusion

Hierarchical inheritance is an important object-oriented programming concept in Java. It allows multiple child classes to reuse common behavior from one parent class while implementing their own specialized functionality. It improves code reuse, supports polymorphism, and helps organize related classes into a clear structure.

Understanding hierarchical inheritance prepares learners to work with real-world class hierarchies, constructor chaining, method overriding, and reusable Java application designs.


Learn Core Java with JustAcademy

Explore the course to strengthen your Java programming fundamentals, object-oriented programming knowledge, and practical coding skills.

Previous Next
whatsapp